package com.cn.hnust.controller;

import java.io.File;
import java.io.IOException;
import java.io.Writer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import com.google.gson.Gson;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/goods")
public class UploadFileDTO {
 
    private Logger logger = Logger.getLogger(UploadFileDTO.class);
   
    @SuppressWarnings("unused")
	@RequestMapping("/upload")
    public void upload(HttpServletResponse response,HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
        request.setCharacterEncoding("UTF-8");
        String user = request.getParameter("user");
        logger.info("user:"+user);
       String trueFileName="";
        if(!file.isEmpty()) {
            String fileName = file.getOriginalFilename();
            String path = null;
            String type = null;
            type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
            if (type != null) {
                if ("GIF".equals(type.toUpperCase())||"PNG".equals(type.toUpperCase())||"JPG".equals(type.toUpperCase())) {
                    String realPath = request.getSession().getServletContext().getRealPath("/");
                    trueFileName = String.valueOf(System.currentTimeMillis()) + fileName;
                    path = "E:\\eclipse-workspace\\mfyy\\src\\main\\webapp\\Lfdshopimg\\" + trueFileName;
                    file.transferTo(new File(path));
                }else {
                 
                }
            }else {
               
            }
        }else {
          
        }
        Gson gson = new Gson();
		String json = gson.toJson(trueFileName);
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "GET,POST");
		response.setContentType("text/json,charset=utf-8");
		response.setCharacterEncoding("utf-8");
		Writer out = response.getWriter();
		out.write(json);
		out.flush();
    }
}